using System.Text;

namespace NFreeMarker.Core
{
    /**
     * An element that represents a conditionally executed block.
     * @author <A HREF="mailto:jon@revusky.com">Jonathan Revusky</A>
     */
    internal sealed class ConditionalBlock : TemplateElement
    {
        internal readonly Expression Condition;
        private readonly bool _isFirst;
        internal bool IsSimple;

        internal ConditionalBlock(Expression condition, TemplateElement nestedBlock, bool isFirst)
        {
            Condition = condition;
            NestedBlock = nestedBlock;
            _isFirst = isFirst;
        }

        internal override void Accept(Environment env)
        {
            if (Condition != null && !Condition.IsTrue(env)) return;

            if (NestedBlock != null)
            {
                env.Visit(NestedBlock);
            }
        }

        public override string GetCanonicalForm()
        {
            var buf = new StringBuilder();
            if (Condition == null)
            {
                buf.Append("<#else");
            }
            else if (_isFirst)
            {
                buf.Append("<#if ");
            }
            else
            {
                buf.Append("<#elseif ");
            }
            if (Condition != null)
            {
                buf.Append(Condition.GetCanonicalForm());
            }
            buf.Append(">");
            if (NestedBlock != null)
            {
                buf.Append(NestedBlock.GetCanonicalForm());
            }
            if (IsSimple)
            {
                buf.Append("</#if>");
            }
            return buf.ToString();
        }

        public override string GetDescription()
        {
            string s = "if ";
            if (Condition == null)
            {
                s = "else ";
            }
            else if (!_isFirst)
            {
                s = "elseif ";
            }
            string cond = Condition != null ? Condition.ToString() : "";
            return s + cond;
        }
    }
}